import { reactive, ref } from "vue";
import { getIdentityListAPI, deleteIdentityAPI } from "@/api/user.ts";
import { ElMessage } from "element-plus";
import type { IdentityItemType } from "@/view/Identity/utils/type.ts";

export default function useUserIdentity() {
  const identityList = ref<IdentityItemType[]>()
  const dialog = ref()
  const pagerParams = reactive({
    limit: 8,
    page: 1
  })
  const total = ref()

  // 获取身份列表
  const getIdentityList = async () => {
    const res = await getIdentityListAPI(pagerParams)
    identityList.value = res.data.identitys
    total.value = res.data.total
  }

  // 添加身份
  const addIdentity = async () => {
    dialog.value.init({}, 0)
  }

  // 编辑身份
  const EditIdentity = (row: any) => {
    dialog.value.init(row, 1)
  }

  // 删除身份
  const deleteIdentity = async (data: any) => {
    await deleteIdentityAPI(data._id)
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    await getIdentityList()
  }

  const handleCurrentPageChange = async (newPage: any) => {
    pagerParams.page = newPage
    await getIdentityList()
  }

  return {
    total,
    pagerParams,
    identityList,
    dialog,
    addIdentity,
    getIdentityList,
    EditIdentity,
    deleteIdentity,
    handleCurrentPageChange,
  }
}
